package com.yips.service.web;

import com.yips.common.constant.UserConstants;
import com.yips.domain.entity.SysUser;
import com.yips.service.SysUserService;
import com.yips.util.SecurityUtils;
import com.yips.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author h2tc01
 * @version 1.0.0
 * 2022/5/10 18:47
 * 用户注册
 */
@Component
@Slf4j
public class SysRegisterService {

    @Autowired
    private SysUserService userService;

    public String register(String email, String username, String password) {
        //注册结果信息
        String msg = "";

        if (StringUtils.isEmpty(username)) {
            msg = "用户名不能为空";
        } else if (StringUtils.isEmpty(password)) {
            msg = "用户密码不能为空";
        } else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            msg = "账户长度必须在2到20个字符之间";
        } else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            msg = "密码长度必须在5到20个字符之间";
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(username))) {
            msg = "保存用户'" + username + "'失败，注册账号已存在";
        } else {
            SysUser sysUser = new SysUser();
            sysUser.setUserName(username);
            sysUser.setNickName(username);
            sysUser.setPassword(SecurityUtils.encryptPassword(password));
            sysUser.setEmail(email);
            boolean regFlag = userService.registerUser(sysUser);
            if (!regFlag) {
                msg = "注册失败,请联系系统管理人员";
            } else {
                log.info("=====>user.register.success");
            }
        }
        return msg;
    }

}
